<?php
require_once(ROOT . LIBRARY .'/tree.class.inc');

function get($params)
{
   $cat = !empty($params['cat']) && is_numeric($params['cat']) ? $params['cat'] : NULL;
   if(empty($cat)) return FALSE;
   
   $_A = new articles();
   
   # SET ORDER
   $allowed_sort = array('title', 'cat', 'position', 'views','sdate');
   $order  = !empty($params['sidx']) && in_array($params['sidx'], $allowed_sort) ? $params['sidx'] : 'position';
   $order  = '`'. $order .'`';
   $order .= !empty($params['sord']) && $params['sord'] == 'asc' ? ' ASC' : ' DESC';
   $_A->setOrder($order);
   
   $set = array();
   $cats_id    = tree_static::getChildrenId($cat);
   if(is_array($cats_id)) $cats_id[] = $cat;
   else $cats_id = array($cat);
   $set['cat'] = array('type' => 'exact', 'value' => $cats_id);
   
   # SET PAGES
   $rows = !empty($params['rows']) && is_numeric($params['rows']) ? $params['rows'] : config::read('items', 'read');
   $page = !empty($params['page']) && is_numeric($params['page']) ? $params['page'] : 1;
   paginator::setCurrentPage($page);
   paginator::setItemsOnPage($rows);
   
   $articles = $_A->getArticles(array('field' => $set));
   
   
   $responce = new stdClass();
   
   if(!empty($articles))
   {
      $pages = paginator::getPages();
      $responce->page    = paginator::getCurrentPage();
      $responce->total   = $pages['pages'];
      $responce->records = $pages['found'];
              
      $i = 0;
      foreach($articles AS $a)
      {
         $responce->rows[$i]['id']   = $a->id;
         $responce->rows[$i]['cell'] = array(
            $a->id,
            $a->title, 
            $a->sdate,
            $a->category->title, 
            $a->views
         );
         $i++;
      }
   }
   
   return $responce;
}

function delete($params)
{
   if(!empty($params) && session::user() && session::user()->hasRole('ADMIN_ACCESS'))
   {
      // TODO: сделать перемещатель в корзину, и заюзать его же для удаления в дереве.
      return TRUE;
   }
   
   return FALSE;
}